<template>
  <div class="bg-white sticky top-0 left-0 z-10 dark:bg-zinc-900 duration-500">
    <ul
      ref="ulTarget"
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden"
    >
      <!-- 滑块 -->
      <li
        ref="sliderTarget"
        class="absolute h-[22px] bg-zinc-900 rounded-lg duration-200 dark:bg-zinc-800"
        :style="sliderStyle"
      ></li>
      <li
        :ref="setItemRef"
        v-for="(item, index) in $store.getters.categorys"
        :key="item.id"
        class="shrink-0 px-1.5 py-0.5 z-10 duration-200"
        :class="index === $store.getters.categorys.length - 1 ? 'mr-4' : ''"
        :style="{
          color: $store.getters.currentCategoryIndex === index ? 'white' : ''
          // color: currentCategoryIndex === index ? 'white' : ''
        }"
        @click="onItemClick(item)"
      >
        {{ item.name }}
      </li>
      <!-- 汉堡按钮 -->
      <li
        @click="isOpenPopup = !isOpenPopup"
        class="z-20 fixed top-0 right-[-1px] h-4 px-1 flex items-center bg-white shadow-l-white dark:bg-zinc-900 dark:shadow-l-zinc"
      >
        <m-svg-icon class="w-1.5 h-1.5" name="hamburger"></m-svg-icon>
      </li>
    </ul>
    <m-popup v-model="isOpenPopup">
      <menu-vue @onItemClick="onItemClick"></menu-vue>
    </m-popup>
  </div>
</template>
<script setup>
import { ref, onBeforeUpdate, watch } from 'vue'
import { useScroll } from '@vueuse/core'
import menuVue from '@/views/main/components/menu/index.vue'
import { useStore } from 'vuex'
const store = useStore()
// const props = defineProps({
//   data: {
//     type: Array,
//     default: () => []
//   }
// })
const sliderTarget = ref(null)
// 滑块
const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '52px'
})
const currentCategoryIndex = ref(0)
// 获取填充的所有 item 元素
let itemRefs = []
// 获取当前项的dom节点
const setItemRef = (el) => {
  if (el) {
    itemRefs.push(el)
  }
}
onBeforeUpdate(() => {
  itemRefs = []
})
watch(
  () => store.getters.currentCategoryIndex,
  (val) => {
    // 获取选中元素的 left、width
    const { left, width } = itemRefs[val].getBoundingClientRect()
    // 为 sliderStyle 设置属性
    sliderStyle.value = {
      // ul 横向滚动位置 + 当前元素的 left 偏移量
      transform: `translateX(${ulScrollLeft.value + left - 10 + 'px'})`,
      width: width + 'px'
    }
  }
)
// 获取 ul 元素，以计算偏移位置
const ulTarget = ref(null)
const { x: ulScrollLeft } = useScroll(ulTarget)
const onItemClick = (item, num = 1) => {
  // currentCategoryIndex.value = index
  store.commit('app/changeCurrentCategory', item)
  isOpenPopup.value = false
  // 如果通过面包屑进入
  if (num === 2) {
    // 获取点击元素的总长度-屏幕宽度 = 需要滚动距离
    let scollLeftLength = itemRefs[index].offsetLeft
    let length = scollLeftLength - window.innerWidth + 100
    // 如果为负数,则滚动的距离为0
    let leftLength = length > 0 ? length : 0
    ulScrollLeft.value = leftLength
  }
}

const isOpenPopup = ref(false)
</script>
